//
//  UINavigationBar+extend.swift
//  scfriend
//
//  Created by wulanzhou on 2017/7/28.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

import Foundation
import UIKit

extension UINavigationBar {
    
    /**************** 通过AssociatedKeys的值定义成员变量 ****************/
    
    //在扩展中通过key来定义成员变量
    fileprivate struct AssociatedKeys {
        static var ch_overlay = "ch_overlay"
    }
    
    //通过AssociatedKeys的值定义成员变量
    var ch_overlay: UIView? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.ch_overlay) as? UIView
        }
        set {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.ch_overlay,
                newValue,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
        }
    }
    
    /**
     设置导航栏背景颜色
     
     - parameter backgroundColor:
     */
    func ch_setBackgroundColor(_ backgroundColor: UIColor) {
        if self.ch_overlay == nil {
            //创建一个背景层
            let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
            self.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
            self.ch_overlay = UIView(frame: CGRect(x: 0, y: -statusBarHeight,
                                                   width: self.bounds.width,
                                                   height: self.bounds.height + statusBarHeight))
            
            self.ch_overlay!.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
            self.ch_overlay!.isUserInteractionEnabled = false
        }
        self.insertSubview(self.ch_overlay!, at: 0)
        self.ch_overlay!.backgroundColor = backgroundColor;
    }

    /// 删除渐变颜色的背景
    func ch_removeBackgroundColor() {
        //删除渐变颜色的背景
        //self.isTranslucent = false
        self.setBackgroundImage(nil, for: UIBarMetrics.default)
        self.ch_overlay?.removeFromSuperview()
        self.ch_overlay = nil;
    }


    //移除navigationBar底部的横线
    func removeUnderline(){
       self.shadowImage = UIImage.init()
    }
}
